﻿using Apps.BLL.YANX;
using Apps.Common;
using Apps.Locale;
using Apps.Models;
using Apps.Web.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace Apps.Web.Areas.YANX.Controllers
{
    public class YANX_RECORDController : BaseController
    {
        YANX_RECORD_BLL bll = new YANX_RECORD_BLL();
        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetList()
        {
            int totalCount = 0;
            string batchaCode = Utils.ObjectToStr(Request["batchCode"]);
            string testCode = Utils.ObjectToStr(Request["testCode"]);
            string name = Utils.ObjectToStr(Request["name"]);
            int pageSize = Utils.ObjToInt(Request["rows"], 15);
            int pageIndex = Utils.ObjToInt(Request["page"], 1);
            string sort = Utils.ObjectToStr(Request["sort"]);
            string order = Utils.ObjectToStr(Request["order"]);
            List<YANX_RECORD> list = bll.GetList(batchaCode, testCode, name, pageIndex, pageSize, sort, order, ref totalCount);
            return Json(new Pagination.PaginationResult<YANX_RECORD>(totalCount, list.ToList()));
        }

        [SupportFilter]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Create(YANX_RECORD model)
        {
            if (model != null && ModelState.IsValid)
            {
                model.YAN_ID = ResultHelper.NewId;

                if (string.IsNullOrEmpty(model.ITEM_NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "标题不能为空!"));
                }
                if (string.IsNullOrEmpty(model.TEST_CODE))
                {
                    return Json(JsonHandler.CreateMessage(0, "化验编码不能为空!"));
                }

                model.BATCH_CODE = bll.GetBatchCode(model.TEST_CODE);
                if (string.IsNullOrEmpty(model.BATCH_CODE))
                {
                    return Json(JsonHandler.CreateMessage(0, "化验编码输入有误，没有找到对应批次!"));
                }
                Regex regex = new Regex("\\s+", RegexOptions.IgnoreCase);
                model.ITEM_NAME = regex.Replace(model.ITEM_NAME, "");
                model.AUDIT_STATUS = "未审核";
                var data = Request.Files;
                if (data == null)
                {
                    return Json(JsonHandler.CreateMessage(0, "请选择一个附件!"));
                }
                if (data.Count <= 0)
                {
                    return Json(JsonHandler.CreateMessage(0, "请选择一个附件!"));
                }
                try
                {
                    HttpFileCollectionBase files = Request.Files;
                    HttpPostedFileBase file = files[0];
                    //获取文件名后缀
                    string extName = Path.GetExtension(file.FileName).ToLower();
                    //获取保存目录的物理路径
                    if (System.IO.Directory.Exists(Server.MapPath("/YANFILES/")) == false)//如果不存在就创建images文件夹
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath("/YANFILES/"));
                    }
                    string path = Server.MapPath("/YANFILES/"); //path为某个文件夹的绝对路径，不要直接保存到数据库
                                                                //    string path = "F:\\TgeoSmart\\Image\\";
                                                                //生成新文件的名称，guid保证某一时刻内图片名唯一（文件不会被覆盖）
                    string fileNewName = model.YAN_ID;
                    string ImageUrl = path + fileNewName + extName;
                    //SaveAs将文件保存到指定文件夹中
                    file.SaveAs(ImageUrl);
                    //此路径为相对路径，只有把相对路径保存到数据库中图片才能正确显示（不加~为相对路径）
                    string url = "\\YANFILES\\" + fileNewName + extName;
                    string jsonstr = Utils.ToJson(model, Formatting.Indented);
                    LogHandler.WriteServiceLog(GetUserId(), jsonstr, "成功", "创建", "YANX_RECORD");

                    model.ITEM_PATH = url;
                    model.ADDTIME = DateTime.Now;
                    model.ADDUSER = GetUserId();
                    bll.Add(model);
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                catch (Exception exception)
                {
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail)); ;
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }

        [SupportFilter]
        public ActionResult Edit(string id)
        {
            YANX_RECORD entity = bll.Info(id);
            ViewData.Model = entity;
            return View(entity);
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(YANX_RECORD model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(model.YAN_ID))
                {
                    return Json(JsonHandler.CreateMessage(0, "未指定编号!"));
                }
                if (string.IsNullOrEmpty(model.ITEM_NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "标题不能为空!"));
                }
                if (string.IsNullOrEmpty(model.TEST_CODE))
                {
                    return Json(JsonHandler.CreateMessage(0, "化验编码不能为空!"));
                }

                model.BATCH_CODE = bll.GetBatchCode(model.TEST_CODE);
                if (string.IsNullOrEmpty(model.BATCH_CODE))
                {
                    return Json(JsonHandler.CreateMessage(0, "化验编码输入有误，没有找到对应批次!"));
                }
                var info = bll.Info(model.YAN_ID);
                if (info.AUDIT_STATUS == "审核通过")
                {
                    return Json(JsonHandler.CreateMessage(0, "已审核的数据不允许修改!"));
                }
                Regex regex = new Regex("\\s+", RegexOptions.IgnoreCase);
                model.ITEM_NAME = regex.Replace(model.ITEM_NAME, "");
                var data = Request.Files;
                if (data != null)
                {
                    if (data.Count > 0)
                    {
                        HttpFileCollectionBase files = Request.Files;
                        HttpPostedFileBase file = files[0];
                        //获取文件名后缀
                        string extName = Path.GetExtension(file.FileName).ToLower();
                        //获取保存目录的物理路径
                        if (System.IO.Directory.Exists(Server.MapPath("/YANFILES/")) == false)//如果不存在就创建images文件夹
                        {
                            System.IO.Directory.CreateDirectory(Server.MapPath("/YANFILES/"));
                        }
                        string path = Server.MapPath("/YANFILES/"); //path为某个文件夹的绝对路径，不要直接保存到数据库
                                                                    //    string path = "F:\\TgeoSmart\\Image\\";
                                                                    //生成新文件的名称，guid保证某一时刻内图片名唯一（文件不会被覆盖）
                        string fileNewName = model.YAN_ID;
                        string ImageUrl = path + fileNewName + extName;
                        //SaveAs将文件保存到指定文件夹中
                        file.SaveAs(ImageUrl);
                        //此路径为相对路径，只有把相对路径保存到数据库中图片才能正确显示（不加~为相对路径）
                        string url = "\\YANFILES\\" + fileNewName + extName;
                        string jsonstr = Utils.ToJson(model, Formatting.Indented);
                        LogHandler.WriteServiceLog(GetUserId(), jsonstr, "成功", "创建", "YANX_RECORD");

                        model.ITEM_PATH = url;
                    }
                }
                try
                {
                    model.ADDTIME = DateTime.Now;
                    model.ADDUSER = GetUserId();
                    bll.Update(model);
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                catch (Exception exception)
                {
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail)); ;
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }

        #region 审核
        [SupportFilter]
        public ActionResult Examine(string dataIds)
        {
            ViewBag.dataIds = dataIds;
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Examine(string dataIds, string examine)
        {
            try
            {
                List<string> ids = dataIds.Split(',').ToList();
                if (ids.Count <= 0)
                {
                    return Json(JsonHandler.CreateMessage(0, "请至少选择一项"));
                }
                if (bll.ExamineData(ids, examine))
                {
                    return Json(JsonHandler.CreateMessage(1, "审核成功"));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    return Json(JsonHandler.CreateMessage(0, "审核失败" + ErrorCol));
                }
            }
            catch
            {
                string ErrorCol = errors.Error;
                return Json(JsonHandler.CreateMessage(0, "审核失败" + ErrorCol));
            }
        }
        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(string id)
        {
            var info = bll.Info(id);
            if (info.AUDIT_STATUS == "审核通过")
            {
                return Json(JsonHandler.CreateMessage(0, "已审核的数据不允许删除!"));
            }
            if (bll.Delete(id))
            {
                LogHandler.WriteServiceLog(GetUserId(), "ID:" + id, "成功", "删除", "YANX_RECORD");
                return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
            }
            else
            {
                string ErrorCol = "【删除失败】";
                LogHandler.WriteServiceLog(GetUserId(), "ID" + id + "," + ErrorCol, "失败", "删除", "YANX_RECORD");
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
            }
        }
        #endregion

    }
}